package com.lxf.clouduser.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lxf.cloudfeign.client.configsClient.ConfigClient;
import com.lxf.clouduser.bean.DeepSeekRequest;
import com.lxf.clouduser.bean.DeepSeekResponse;
import com.lxf.clouduser.service.DeepSeekService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author 罗兴发
 * @data 2025/2/25 11:33
 * @description：deepseek-业务实现层
 */
@Service
public class DeepSeekServiceImpl implements DeepSeekService {

    @Resource
    private ConfigClient configClient;

    private final RestTemplate restTemplate = new RestTemplate();

    public String callDeepSeek(JSONObject json) {
        //获取apiKey
        String apiKey = configClient.getDSApiKey();
        //获取apiUrl
        String apiUrl = configClient.getDSApiUrl();
        //获取apiModel
        String apiModel = configClient.getDSApiModel();

        //咨询的问题内容
        String userMessage = json.getString("message");

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        headers.set("Authorization", "Bearer " + apiKey);
        List<DeepSeekRequest.Message> user = Collections.unmodifiableList(Arrays.asList(new DeepSeekRequest.Message("user", userMessage)));

        // 构建请求体
        DeepSeekRequest request = new DeepSeekRequest();
        request.setModel(apiModel);
        request.setMessages(user);

        // 发送请求
        HttpEntity<DeepSeekRequest> entity = new HttpEntity<>(request, headers);
        ResponseEntity<DeepSeekResponse> response = restTemplate.exchange(
                apiUrl, HttpMethod.POST, entity, DeepSeekResponse.class);

        // 解析响应
        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            return response.getBody().getChoices().get(0).getMessage().getContent();
        } else {
            throw new RuntimeException("Failed to call DeepSeek API: " + response.getStatusCode());
        }
    }
}
